#! /usr/bin/python
# -*- coding: cp1250 -*-

import re
import string
import sys
import glob
import os
import time
import pepe.p_txt.bigtxt as bt
import pepe.p_datetime.stopw as pds

iso_time_now = lambda : time.strftime ("%Y-%m-%dT%H:%M:%S", time.localtime())
fwSlash = lambda x: re.sub(r'\\', '/', x)

def info(file, cdelimiter='', hasHeader=True, ignoreEmptyRows=True):
    """ Get info about text file (passed and reused as dictionary):

        @FILE           : full path input file name
        @COLUMNS        : columns count
        @ROWS           : rows count
        @CSPAN          : columns header names and spans
        @RUN_DURATION   : time needed to process data
        @RUN_TIMESTAMP  : script run timestamp 
    """
    counter = 0
    info = { '@FILE':"%s/%s"%(fwSlash(os.getcwd()), file)
            ,'@COLUMNS':[], '@CSPAN':{}, '@CDELR': cdelimiter
            ,'@HASHDR':hasHeader}

    # stop watches
    sw = pds.SW()
    sw.start()

    for line in bt.lines(file):
        line = re.sub('\n', '', line)

        # empty lines
        if line == '' and ignoreEmptyRows:  pass
        else:
            counter += 1

            columns = string.split(line, cdelimiter)
            if len(columns) not in info['@COLUMNS']:
                info['@COLUMNS'].append(len(columns))

            for i,v in enumerate(columns):
                i = 'c' + string.zfill(str(i), 3)
                # if header
                if counter == 1 and hasHeader:
                    info['@CSPAN'][i] = {'HEADER':v, 'SPAN':0}
                elif counter == 1 and not hasHeader:
                    info['@CSPAN'][i] = {'HEADER':i, 'SPAN':0}
                else:
                    span = {'SPAN':len(string.strip(v))}
                    if span > info['@CSPAN'][i]['SPAN']:
                        info['@CSPAN'][i].update(span)
    info.update({'@ROWS':counter})
    sw.stop()
    info.update({'@RUN_DURATION':sw.pp()})
    info.update({'@RUN_TIMESTAMP':iso_time_now()})

    return info

def pp(i):
    """ Pretty print INFO dictionary
    """
    print '-'*35
    for k in sorted(i.keys()):
        if k in ('@CSPAN'):
            cs = i[k]
        else:
            print k, i[k]
    print '@CSPAN'
    for c in sorted(cs.keys()):
        print '\t', c, cs[c]
    print """
    import pepe.p_utils.txti as ti
    d = ti.info(file='new.txt', cdelimiter='^',
                hasHeader=True, ignoreEmptyRows=True)
    ti.pp(d)
    """

def ui():
    """ User interface : if runned per command line
    """
    # input file name
    if len(sys.argv) == 1:  f = str(raw_input("Enter a file name: "))
    else:                   f = sys.argv[1]
    # column delimiter
    d = str(raw_input("Enter a column delimiter (default '^'): "))
    # file has header ?
    hh = str(raw_input("File has header (y/n; default y): "))
    # ignore empty rows
    ie = str(raw_input("Ignore empty rows (y/n; default y): "))

    if d in (''): d = '^'
    if hh in ('True', 'true', 'y', 'Y', ''): hh = True
    if ie in ('True', 'true', 'y', 'Y', ''): ie = True

    return info(f, d, hh, ie)

if __name__ == '__main__':
    """ """
    pp(ui())
